/**
 *
 */
var __sforce;

function setupSforce(callback) {
  if (__sforce) callback(__sforce);

  var doc = this.selectSfdcDoc();
  if (!doc) return;
  var baseUrl = doc.location.href.split('/').slice(0, 3).join('/');
  var scriptUrl = baseUrl + '/soap/ajax/13.0/connection.js';
  var serverUrl = baseUrl + '/services/Soap/u/13.0';
  var m = doc.cookie.match(/(^|;?s*)sid=([^;]*);/);
  if (!m) return;
  var sid = m[2];
  jQuery.get(scriptUrl, {}, function(text) {
     var alert = function(msg){ CmdUtils.log(msg) };
     eval(text);
     sforce.connection.sessionId = sid;
     sforce.connection.serverUrl = serverUrl;
     callback(sforce);
  });
}

function selectSfdcDoc() {
  for (var i=0, tabs=Application.activeWindow.tabs, len=tabs.length; i<len; i++) {
    if (/^https?:\/\/(na[\d]+|ap|emea|tapp0|ssl)\.salesforce\.com\//.test(tabs[i].document.location.href)) {
      return tabs[i].document;
    }
  }
}

/**
 *
 */
var mextractrUrl = 'http://api.emetadata.net/mextractr';
var apiKey = '7288372075BC74056F9C9F3F1B0B73ECB0C839C7';

var Mextractr = function() { 
}

Mextractr.prototype = {
  extract : function(text, callback) {
    jQuery.ajax({
      type: "POST",
      url : mextractrUrl,
      data: {
        output : 'atom',
        apikey : apiKey,
        text : text.replace(/\\n/g,' ')
      },
      dataType: "xml",
      error: function(error) {
        displayMessage(error)
      },
      success: extractMetadata
    });

    function extractMetadata(doc) {
      var result = {}
      result.whos = Array.prototype.slice.apply(doc.getElementsByTagName('gd:who')).map(function(w) { 
        var w = w.getAttribute('valueString');
        var isCompany = w.charAt(0)=='*';
        return { value : isCompany ? w.substring(1) : w, isCompany : isCompany };
      });
      result.wheres = Array.prototype.slice.apply(doc.getElementsByTagName('gd:where')).map(function(w) { 
        return { value : w.getAttribute('valueString') }
      });
      result.whens = Array.prototype.slice.apply(doc.getElementsByTagName('gd:when')).map(function(w) { 
        return { value : w.getAttribute('valueString'),
                 startTime : w.getAttribute('startTime'), 
                 endTime : w.getAttribute('endTime') };
      });

      callback(result);
    }

  }
}


function showSubmitDialog(document) {
  var baseUrl = 'http://sfdc-ubiquity.googlecode.com/svn/trunk/';

  var iframeId = '_ubiquity_ifr';
  if (document.getElementById(iframeId)) return;
  ifr = document.createElement('iframe');
  ifr.id = iframeId;
  ifr.style.position = 'absolute';
  ifr.style.zIndex = 99999;
  ifr.style.top = ifr.style.left = '0px';
  ifr.style.width = '100%';
  ifr.style.height = document.body.scrollHeight+'px';
  ifr.frameBorder='no';
  document.body.appendChild(ifr);
  with(ifr.contentWindow.document) {
    open();
    write(['<html><head>',
    '<link type="text/css" rel="stylesheet" href="'+baseUrl+'/ext-2.2/resources/css/ext-all.css" />',
    '<script type="text/javascript" src="'+baseUrl+'/ext-2.2/adapter/ext/ext-base.js"></script>',
    '<script type="text/javascript" src="'+baseUrl+'/ext-2.2/ext-all.js"></script>',
    '<script type="text/javascript" src="'+baseUrl+'/extapp.js"></script>',
    '</head>',
    '<body></body></html>'].join(''));
    close();
  }
  return ifr.contentWindow;
}

/**
 *
 */
CmdUtils.CreateCommand({
  name: "salestractr",
  takes: {
    "text" : noun_arb_text
  },
  execute: function(dobj) {
    setupSforce(function(sforce) {
      var ifrwin = showSubmitDialog(CmdUtils.getDocumentInsecure());
      CmdUtils.getWindowInsecure().ubqCtx = {
        text : dobj.text,
        sforce : sforce,
        mextractr : new Mextractr()
      }
    });
  }
})

